package com.fsy.its.netty.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class DtuDecoderFactory {

    private Map<String, Object> decoders = new HashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    public void addDecoderInstance(String brand, String model, Object decoderBean) throws Exception {
        if( brand==null || brand.isEmpty() ) {
            throw new Exception("Brand of fire host for the decoder must specified.");
        }

        //品牌和型号用点连接作为key值将decoder保存到map中
        //如果不指定型号，只将品牌作为key值，表示这个decoder适合这个品牌的所有型号
        StringBuilder key = new StringBuilder(brand.toLowerCase());
        if( model!=null && !model.isEmpty() ) {
            key.append(".");
            key.append(model.toLowerCase());
        }
        decoders.put(key.toString(), decoderBean);
    }

    public Object getDecoder(String brand, String model) {
        if( model == null ) {
            model = "";
        }
        //先按品牌和型号精确查找
        StringBuilder key = new StringBuilder(brand.toLowerCase());
        key.append(".");
        key.append(model.toLowerCase());
        Object decoder = decoders.get(key.toString());

        //再用品牌查找
        if( decoder == null ) {
            decoder = decoders.get(brand.toLowerCase());
        }

        //从容器里获取bean，每次会创建新的实例（decoder的@Scope要定义为prototype）
        return decoder==null ? null : applicationContext.getBean(decoder.getClass());
    }
}
